package com.hzcx.app.simplechat.ui.chat;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.ui.chat.adapter.ChatQuickMsgManagerAdapter;
import com.hzcx.app.simplechat.ui.chat.bean.ChatQuickMsgBean;
import com.hzcx.app.simplechat.ui.chat.contract.ChatQuickMsgManagerContract;
import com.hzcx.app.simplechat.ui.chat.event.ChatQuickMsgRefreshEvent;
import com.hzcx.app.simplechat.ui.chat.presenter.ChatQuickMsgManagerPresenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 快捷回复管理界面
 */
public class ChatQuickMsgManagerActivity extends BaseActivity<ChatQuickMsgManagerPresenter> implements ChatQuickMsgManagerContract.View {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.rv_quick_msg)
    RecyclerView rvQuickMsg;

    private List<ChatQuickMsgBean> quickMsgData;
    private ChatQuickMsgManagerAdapter quickAdapter;
    private boolean isMove = false;

    @Override
    public int getLayout() {
        return R.layout.activity_chat_quick_msg_manager;
    }

    @Override
    public void initPresenter() {
        mPresenter = new ChatQuickMsgManagerPresenter();
    }

    @Override
    public void initView() {
        tvTitle.setText("管理常用语");
        tvTitleRight.setText("排序");

        quickMsgData = new ArrayList<>();
        quickAdapter = new ChatQuickMsgManagerAdapter(quickMsgData);
        rvQuickMsg.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvQuickMsg.setAdapter(quickAdapter);
    }

    @Override
    public void initData() {
        mPresenter.getQuickMsgList(this);

        quickAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.tv_delete: // 删除
                    mPresenter.deleteChatQuickMsg(ChatQuickMsgManagerActivity.this, quickMsgData.get(position).getReply_id(), position);
                    break;

                case R.id.tv_edit: // 编辑
                    startActivity(new Intent(ChatQuickMsgManagerActivity.this, ChatQuickMsgAddActivity.class)
                            .putExtra(ChatQuickMsgAddActivity.INTENT_ID, quickMsgData.get(position).getReply_id() + "")
                            .putExtra(ChatQuickMsgAddActivity.INTENT_CONTENT, quickMsgData.get(position).getMaincontent())
                            .putExtra(ChatQuickMsgAddActivity.INTENT_IMAGE_URL, new Gson().toJson(quickMsgData.get(position))));
                    break;
            }
        });
    }

    @OnClick({R.id.tv_title_right})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_title_right:
                if (!isMove) {
                    tvTitleRight.setText("完成");
                    helper.attachToRecyclerView(rvQuickMsg);
                    quickAdapter.setIsLeft(false);
                    isMove = true;
                } else {
                    mPresenter.moveChatQuickMsg(this, quickMsgData);
                }
                break;
        }
    }

    /**
     * 快捷列表获取成功
     *
     * @param data
     */
    @Override
    public void quickMsgResult(List<ChatQuickMsgBean> data) {
        try {
            quickMsgData.clear();
            quickMsgData.addAll(data);
            quickAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除快捷回复成功
     *
     * @param pos
     */
    @Override
    public void deleteSuccess(int pos) {
        showError("删除成功");
        quickMsgData.remove(pos);
        quickAdapter.notifyDataSetChanged();
        EventBus.getDefault().post(new ChatQuickMsgRefreshEvent(1, pos));
    }

    /**
     * 排序成功
     */
    @Override
    public void moveSuccess() {
        showError("排序成功");
        EventBus.getDefault().post(new ChatQuickMsgRefreshEvent(3, 0));
        isMove = false;
        helper.attachToRecyclerView(null);
        quickAdapter.setIsLeft(true);
        tvTitleRight.setText("排序");
    }

    /**
     * 刷新快捷回复列表
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshQuickMsg(ChatQuickMsgRefreshEvent event) {
        if (event.getTag() == 0) {
            mPresenter.getQuickMsgList(this);
        }
    }

    ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int dragFrlg = 0;
            if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                dragFrlg = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            } else if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
                dragFrlg = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            }
            return makeMovementFlags(dragFrlg, 0);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            //滑动事件  下面注释的代码，滑动后数据和条目错乱，被舍弃
//            Collections.swap(datas,viewHolder.getAdapterPosition(),target.getAdapterPosition());
//            ap.notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition());

            //得到当拖拽的viewHolder的Position
            int fromPosition = viewHolder.getAdapterPosition();
            //拿到当前拖拽到的item的viewHolder
            int toPosition = target.getAdapterPosition();
            if (fromPosition < toPosition) {
                for (int i = fromPosition; i < toPosition; i++) {
                    Collections.swap(quickMsgData, i, i + 1);
                }
            } else {
                for (int i = fromPosition; i > toPosition; i--) {
                    Collections.swap(quickMsgData, i, i - 1);
                }
            }
            quickAdapter.notifyItemMoved(fromPosition, toPosition);
            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            //侧滑删除可以使用；
        }

        @Override
        public boolean isLongPressDragEnabled() {
            return true;
        }

        /**
         * 长按选中Item的时候开始调用
         * 长按高亮
         * @param viewHolder
         * @param actionState
         */
        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                //获取系统震动服务//震动70毫秒
                Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                vib.vibrate(70);
            }
            super.onSelectedChanged(viewHolder, actionState);
        }

        /**
         * 手指松开的时候还原高亮
         * @param recyclerView
         * @param viewHolder
         */
        @Override
        public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);
            viewHolder.itemView.setBackgroundColor(0);
            quickAdapter.notifyDataSetChanged();  //完成拖动后刷新适配器，这样拖动后删除就不会错乱
        }
    });
}
